package com.itheima.reggie.contorller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String basepath;
//hongshaorou  .jpg
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String s = UUID.randomUUID().toString() + substring;
        File dir = new File(basepath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file1 = new File(dir, s);
        try {
            file.transferTo(file1);
            return R.success(s);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传时出现问题");
        }
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse resp) {
        File file = new File(basepath, name);

        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream outputStream = resp.getOutputStream();
            int len = 0;
            byte[] bytes = new byte[8 * 1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
            fileInputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
